package com.cuitrip.business.user;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.cuitrip.apiservice.ServiceBusiness;
import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.location.model.AreaMode;
import com.cuitrip.business.location.model.LocationMode;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.component.item.IndexBar;
import com.cuitrip.service.R;
import com.cuitrip.util.I118Util;
import com.cuitrip.util.PinYinUtil;
import com.cuitrip.util.PlatformUtil;
import com.cuitrip.util.adapter.CTListAdapter;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.proxy.ApiProxy;
import com.lab.network.proxy.ApiProxyBuilder;
import com.lab.network.proxy.ApiProxyCallBack;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.LogHelper;
import com.lab.utils.MessageUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import rx.Observable;

/**
 * Created by MiJack on 2015/10/14.
 */
public class ChooseCityActivity extends CustomUiFragmentActivity {
    ListView listView;
    LocationAdapter adapter;
    public static final String CITY_KEY = "CITY_KEY";
    public static final String ABBR_KEY = "ABBR_KEY";
    Stack<State> stack;
    ApiProxy apiProxy;
    public static final int RESULT_CODE_CHOOSE_CITY = 0x0113;
    public static final String KEY_CHOOSE_CITY = "KEY_CHOOSE_CITY";
    public static final int REQUEST_CODE_CHANGE_USER_CITY = 0x0111;
    public static final int REQUEST_CODE_CHOOSE_CITY = 0x0112;
    public static final String KEY_PROVINCE_NAME = "KEY_PROVINCE_NAME";
    public static final String KEY_PROVINCE_ABBR = "KEY_PROVINCE_ABBR";
    public static final String KEY_CITY_NAME = "KEY_CITY_NAME";
    public static final String KEY_CITY_ABBR = "KEY_CITY_ABBR";
    public static final String KEY_LIST_TYPE = "KEY_LIST_TYPE";
    public static final String KEY_SAVE_CITY = "KEY_SAVE_CITY";
    private boolean saveCityFlag;
    private String cityAbbr;
    private String nextTilte;
    private String city;
    private String listType;
    private IndexBar mIndexBar;
    private LocationMode locationMode;
    private TextView index;
    private HashMap<String, Integer> indexMap = new HashMap<String, Integer>();
    private ArrayList<String> list;
    private ArrayList<String> indexList;
    private String countryAbbr;
    private boolean chooseCityFlag;


    public  static  void changUserCity(Activity activity){
        Intent intent = new Intent(activity ,ChooseCityActivity.class);
        intent.putExtra(KEY_SAVE_CITY , true );
        intent.putExtra(KEY_LIST_TYPE , ServiceBusiness.USER_TYPE);
        activity.startActivityForResult(intent , REQUEST_CODE_CHANGE_USER_CITY);
    }
    public static void chooseUserCity(Activity activity){
        Intent intent = new Intent(activity ,ChooseCityActivity.class);
        intent.putExtra(KEY_CHOOSE_CITY , true );
        intent.putExtra(KEY_LIST_TYPE , ServiceBusiness.USER_TYPE);
        activity.startActivityForResult(intent , REQUEST_CODE_CHANGE_USER_CITY);
    }

    public static void requestCity(Activity activity) {
        Intent intent = new Intent(activity,ChooseCityActivity.class);
        intent.putExtra(KEY_SAVE_CITY,false);
        intent.putExtra(KEY_LIST_TYPE,ServiceBusiness.SERVICE_TYPE);
        activity.startActivityForResult(intent,REQUEST_CODE_CHOOSE_CITY);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_choose_city);
    }


    @Override
    public void initView() {
        chooseCityFlag=getIntent().getBooleanExtra(KEY_CHOOSE_CITY,false);
        saveCityFlag = getIntent().getBooleanExtra(KEY_SAVE_CITY, false);
        listType = getIntent().getStringExtra(KEY_LIST_TYPE);
        apiProxy= ApiProxyBuilder.getBuilder().addApiCallBack(ApiManager.GET_COUNTRY_CITY,countryCallBack)
                .addApiCallBack(ApiManager.MODIFY_USERINFO, userInfoCallback).build();
        listView = (ListView) findViewById(R.id.listView);
        mIndexBar = (IndexBar) findViewById(R.id.index_bar);
        adapter = new LocationAdapter();
        stack = new Stack<>();
        nextTilte = getString(R.string.setting_country);
        request(null, nextTilte,"");
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AreaMode item = adapter.getItem(position);
                if (item.getHasChild()==0) {
                    //不存在下一级
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 1; i < stack.size(); i++) {
                        stringBuilder.append(stack.get(i).title).append("-");
                    }
                    if(stack.size()>1){
                        countryAbbr = stack.get(1).countryAbbr;
                    }else{
                        countryAbbr = item.getAbbr();
                    }
                    stringBuilder.append(item.getName());
                    city = stringBuilder.toString();
                    if(chooseCityFlag) {
                        Intent intent = new Intent();
                        intent.putExtra("city", formatCityName(item.getAbbr(), city));
                        intent.putExtra("cityAbbr", item.getAbbr());//city code
                        intent.putExtra("country", countryAbbr);
                        setResult(RESULT_CODE_CHOOSE_CITY, intent);
                        finish();

                    }else if (saveCityFlag) {
                        saveCity(item.getAbbr());
                    } else {
                        Intent intent = new Intent();
                        intent.putExtra(CITY_KEY, city);
                        intent.putExtra(ABBR_KEY,item.getAbbr());
                        AreaMode province;
                        if (stack.size()>1){
                            province=stack.get(1).areaMode;
                            intent.putExtra(KEY_PROVINCE_NAME,province.getName());
                            intent.putExtra(KEY_PROVINCE_ABBR,province.getAbbr());
                            if (stack.size()>2){
                                AreaMode city=stack.get(1).areaMode;
                                intent.putExtra(KEY_CITY_NAME,city.getName());
                                intent.putExtra(KEY_CITY_ABBR,city.getAbbr());
                            }
                        }

                        setResult(RESULT_OK, intent);
                        finish();
                    }
                } else {
                    request(item , item.getName(),item.getAbbr());
                }
            }
        });
    }

    private void saveCity(String cityAbbr) {
        this.cityAbbr = cityAbbr;
        Map<String, String> params = new HashMap<>();
        //城市修改
        params.put("city", formatCityName(cityAbbr,city));//台湾-台北
        params.put("cityAbbr", cityAbbr);//city code
        params.put("country",countryAbbr);
        UserBusiness.updateProfile(apiProxy, params);
    }

    private String formatCityName(String cityAbbr, String city) {
        String[] citys = city.split("-");
        StringBuilder sb = new StringBuilder();
        sb.append(citys[0]);
        String[] abbrs = new String[]{"CN-11", "CN-12", "CN-50", "CN-31"};
        //1、判断是否为省辖市
        boolean isZXS = false;
        for (int i = 0; i < abbrs.length; i++) {
            String abbr = abbrs[i];
            if (cityAbbr.startsWith(abbr)) {
                isZXS = true;
            }
        }
        if (isZXS) {
            if (citys.length > 1) {
                sb.append("-").append(citys[1]);
            }
            return sb.toString();
        }
        //普通城市
        if (stack.size() > 2) {
            sb.append("-").append(citys[citys.length - 1]);
        } else {
            for (int i = 1 ; i < citys.length ; i++){
                sb.append("-").append(citys[i]);
            }
        }
        return sb.toString();
    }

    IProxyCallback userInfoCallback=new ApiProxyCallBack<CtUserInfo>(){
        @Override
        public boolean onSuccess(CtUserInfo data, CtApiResponse response) {
            hideLoading();
            LogHelper.e("omg", "request" + response.result);
            LogHelper.e("omg", "data ！＝null" + (data != null) + "|" + data);
            //格式正确
            LogHelper.e("omg", "data instanceof LocationMode");
            LoginInstance.updateProfile(AppCoreRuntime.context, data, false);
            Intent intent = new Intent();
            intent.putExtra(CITY_KEY, city);
            intent.putExtra(ABBR_KEY, cityAbbr);
            setResult(RESULT_OK, intent);
            finish();
            return super.onSuccess(data, response);
        }

        @Override
        public boolean onFaild(CtApiResponse response) {
            hideLoading();
            String msg;
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                msg = response.msg;
            } else {
                msg = PlatformUtil.getInstance().getString(R.string.feedback_data_err);
            }
            MessageUtils.showToast(msg);
            return super.onFaild(response);
        }
    };

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    private void request(AreaMode location, String title,String countryAbbrParam) {
        State state = new State();
        state.title = title;
        state.areaMode = location;
        state.countryAbbr = countryAbbrParam;
        stack.push(state);
        showNoCancelDialog();
        LogHelper.e("omg", " location == null: " + (location == null ? "true" : "false | " + location));
        ServiceBusiness.getCountryCity(apiProxy, I118Util.getLanguageTag(),location==null?"":location.getAbbr(),listType);
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarMiddleAreaName = getString(R.string.setting_country);
        return config;
    }

    @Override
    public void onTopbarLeftPress() {
        if (stack.isEmpty()){
            finish();
            return;
        }
        stack.pop();
        if (stack.empty()) {
            this.setResult(RESULT_CANCELED);
            this.finish();
        } else {
            State state =stack.peek();
            mTopbarMiddleArea.setText(state.title);
            renderData(state.locationMode);
            mIndexBar.setLetters(state.index);
            mIndexBar.test();
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            onTopbarLeftPress();
            return  true;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        onTopbarLeftPress();
    }

    private void renderData(LocationMode locationMode) {
        adapter.setLocationMode(locationMode);
    }

    class State {
        ArrayList<String> index;
        String title;
        String countryAbbr;
        LocationMode locationMode;
        AreaMode areaMode;
        public boolean isStart() {
            return locationMode.getLocationType().equals("0");
        }
    }

    IProxyCallback countryCallBack=new ApiProxyCallBack(){

        @Override
        public boolean onSuccess(Object data, CtApiResponse response) {
            if (ApiManager.GET_COUNTRY_CITY.equals(response.getApiName())){
            LogHelper.e("omg", "request" + response.result);
            LogHelper.e("omg", "data ！＝null" + (data != null) + "|" + data);
            listView.setVisibility(View.VISIBLE);
            if (data instanceof LocationMode) {
                LogHelper.e("omg", "data instanceof");
                locationMode = ((LocationMode) data);
                if (locationMode.getContent() == null || locationMode.getContent().isEmpty()) {
                    LogHelper.e("omg", "data content empty");
                    return false;
                }else{
                    Collections.sort(locationMode.getContent());
                    indexMap.clear();
                    indexList = getIndexList(locationMode, indexMap);
                    mIndexBar.setLetters(indexList);
                    mIndexBar.test();
                    adapter = new LocationAdapter();
                    listView.setAdapter(adapter);
                    mIndexBar.setListView(listView);

                }
                hideNoCancelDialog();
                //数据存储
                State peek = stack.peek();
                peek.index=indexList;
                peek.locationMode = locationMode;
                renderData(locationMode);
                mTopbarMiddleArea.setText(peek.title);
            } else {
                String msg = PlatformUtil.getInstance().getString(R.string.feedback_data_err);
                MessageUtils.showToast(msg);
                }
            }
            return super.onSuccess(data, response);
        }

        @Override
        public boolean onFaild(CtApiResponse response) {
            if (ApiManager.GET_COUNTRY_CITY.equals(response.getApiName())){
            stack.pop();
            hideNoCancelDialog();
            String msg;
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                msg = response.msg;
            } else {
                msg = PlatformUtil.getInstance().getString(R.string.feedback_data_err);
            }
            MessageUtils.showToast(msg);
            }
            return super.onFaild(response);
        }
    };


    private class LocationAdapter extends CTListAdapter implements Indexer{
        LocationMode locationMode;
        private String mFirstChar;
        private String mPreFirstChar;
        public LocationMode getLocationMode() {
            return locationMode;
        }

        public void setLocationMode(LocationMode locationMode) {
            this.locationMode = locationMode;
            this.notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return locationMode == null ? 0 : locationMode.getContent().size();
        }

        @Override
        public AreaMode getItem(int position) {
            return locationMode.getContent().get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;

            if (convertView == null) {

                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_city_choose, parent, false);
                holder = new ViewHolder();
                convertView.setTag(holder);
                holder.index= (TextView) convertView.findViewById(R.id.index);
                holder.country = (TextView) convertView.findViewById(R.id.item_name);
                holder.icon = (IconTextView) convertView.findViewById(R.id.icon);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            AreaMode item = getItem(position);
            if(position == 0) {
                mPreFirstChar = "-";
            }else {
                String preFirstChar = PinYinUtil.toPinyin(locationMode.getContent().get(position - 1).getName());
                if (!TextUtils.isEmpty(preFirstChar)){
                    mPreFirstChar = String.valueOf(preFirstChar.charAt(0)) ;
                }
            }
            String pinYin =  PinYinUtil.toPinyin(item.getName());

            if (!TextUtils.isEmpty(pinYin)){
                mFirstChar =String.valueOf(pinYin.charAt(0));
            }
            if(!TextUtils.equals(mPreFirstChar, mFirstChar)){
                holder.index.setVisibility(View.VISIBLE);
                holder.index.setText("      "+mFirstChar);
            }else{
                holder.index.setVisibility(View.GONE);
            }
            holder.country.setText(item.getName());
            holder.icon.setVisibility(item. getHasChild()==0? View.INVISIBLE : View.VISIBLE);
            return convertView;
        }

        @Override
        public int getStartPositionOfSection(String section) {
            if(indexMap.containsKey(section))
                return indexMap.get(section);
            return -1;
        }


        class ViewHolder {
            TextView country;
            IconTextView icon;
            TextView index;
        }
    }

    private ArrayList<String> getIndexList(LocationMode locationMode,HashMap<String, Integer> indexMap){
        ArrayList<String> indexList=new ArrayList<>();
        indexList.clear();
        for(int i=0;i<locationMode.getContent().size();++i) {
            String section = String.valueOf(PinYinUtil.toPinyin(locationMode.getContent().get(i).getName()).charAt(0));
            if(!indexMap.containsKey(section)){
                indexMap.put(section, i);
                indexList.add(section);
            }
        }
        return indexList;
    }
}
